package com.mjk.manager.magicapi.conf.interceptor;

import cn.hutool.core.map.MapUtil;
import com.mjk.common.base.error.BeeError;
import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.core.jdbc.service.plus.idbservice.BeeDBService;
import com.mjk.common.core.redis.limiter.RedisLimiter;
import com.mjk.common.tools.interceptor.DefaultInterceptorChain;
import com.mjk.common.tools.logger.BizLogger;
import com.mjk.common.tools.springextend.BeeSpringBean;
import com.mjk.common.util.LicenseUtils;
import com.mjk.common.web.getway.constns.GetWayError;
import com.mjk.common.web.getway.restful.interceptor.GetWayInterceptorReq;
import com.mjk.common.web.getway.restful.interceptor.annotation.BeeGetWayInterceptor;
import com.mjk.common.web.getway.restful.interceptor.type.GetWayInterceptorType;
import com.mjk.common.web.getway.restful.interceptor.type.commons.impl.GetWayLicenseAuthInterceptor;
import com.mjk.common.web.getway.restful.prototal.BaseGetwayInterceptor;
import com.mjk.manager.magicapi.core.core.context.RequestEntity;
import com.mjk.manager.magicapi.core.core.interceptor.RequestInterceptor;
import com.mjk.manager.magicapi.core.core.logging.LogbackLoggerContext;
import com.mjk.manager.magicapi.core.core.model.ApiInfo;
import com.mjk.manager.magicapi.core.core.servlet.MagicHttpServletRequest;
import com.mjk.manager.magicapi.core.core.servlet.MagicHttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.ssssssss.script.MagicScriptContext;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 自定义请求拦截器，可实现鉴权
 * https://ssssssss.org/magic-api/pages/senior/interceptor/
 *
 * @see RequestInterceptor
 */
public class CustomRequestInterceptor implements RequestInterceptor {


    private static final Logger logger = LoggerFactory.getLogger(CustomRequestInterceptor.class);

    @Autowired
    private BeeDBService beeDBService;
    @Autowired
    private RedisLimiter redisLimiter;
    /**
     * 接口请求之前
     *
     * @param requestEntity    请求信息
     */
    @Override
    public Object preHandle(RequestEntity requestEntity) throws Exception {
        BaseGetwayInterceptor interceptor = (BaseGetwayInterceptor) BeeSpringBean.getBean("getGetWayInterceptor");
        GetWayInterceptorReq req = converRequestEntity(requestEntity);
        DefaultInterceptorChain<GetWayInterceptorReq, BeeResponse> chains = interceptor.getChains().get(GetWayInterceptorType.MAGICAPI.getProto());
        chains.setInterceptors(chains.getInterceptors().stream().filter(item->{
                    BeeGetWayInterceptor annotaion = item.getClass().getAnnotation(BeeGetWayInterceptor.class);
                    GetWayInterceptorType[] types = annotaion.interceptorType();
                    boolean isfilter = false;
                    for(GetWayInterceptorType tmp : types){
                        if(tmp.compareTo(GetWayInterceptorType.MAGICAPI)==0){
                            isfilter = true;
                            break;
                        }
                    }
                    return isfilter;
                }
        ).collect(Collectors.toList()));
        if(!CollectionUtils.isEmpty(chains.getInterceptors())) {
            BeeResponse rsp = chains.proceed(req);
        	if(rsp!=null && !rsp.getCode().equals(BeeError.BEE_SUC.getCode())){
                return rsp;
            }
        }
        if (BeeSpringBean.exitBean(GetWayLicenseAuthInterceptor.class)) {
            if (!LicenseUtils.checkLicense()) {
                BeeResponse reponse = GetWayError.LICENSE_ERROR.tranceError("License申请码为:" + LicenseUtils.getReqCode());
                reponse.setMsg(reponse.getData().toString());
                return reponse;
            }
        }

        LogbackLoggerContext.startLog(requestEntity.getParameters(), "1");
        return null;
    }

    /**
     * 接口执行之后
     *
     * @param info    接口信息
     * @param context 变量信息
     * @param value   即将要返回到页面的值
     */
    @Override
    public Object postHandle(ApiInfo info, MagicScriptContext context, Object value, MagicHttpServletRequest request, MagicHttpServletResponse response) throws Exception {
//        logger.info("{} 执行完毕，返回结果:{}", info.getName(), value);
        //保存结果到数据库 删除ThreadLocal
        try {
            LogbackLoggerContext.endLog(value, info.getPath(), info.getGroupName(), info.getName());
        } catch (Exception e) {
            BizLogger.error(e);
        }
        return null;
    }
    private GetWayInterceptorReq converRequestEntity(RequestEntity entity) {
        GetWayInterceptorReq req = new GetWayInterceptorReq();
        req.setParams(entity.getParameters());
        req.setRequest(entity.getHttpRequest());
        req.setResponse(entity.getHttpResponse());
        if (MapUtil.isNotEmpty(entity.getHeaders())) {
            Map<String, String> resultMap = new HashMap();
            for(Map.Entry<String,Object> entry : entity.getHeaders().entrySet()){
                resultMap.put(entry.getKey(),entry.getValue() != null ? entry.getValue().toString() : null);
            }
            req.setHeadParams(resultMap);
        }
        return req;
    }
}
